package com.zhongwang.mms.module.jiaGongSemi.service;

import com.zhongwang.mms.common.JsonResult;
import com.zhongwang.mms.gen.entity.HInventory;
import com.zhongwang.mms.gen.entity.HOrder;
import com.zhongwang.mms.gen.entity.TWarehouseInfo;
import com.zhongwang.mms.gen.entity.User;
import com.zhongwang.mms.module.basic.service.BoardService;
import com.zhongwang.mms.module.half.model.HInBillModel;
import com.zhongwang.mms.module.half.model.HInventoryQueryModel;
import com.zhongwang.mms.module.half.model.HOrderDetailModel;
import com.zhongwang.mms.module.half.model.PrintListModel;
import com.zhongwang.mms.module.jiaGongSemi.dao.SemiInDao;
import com.zhongwang.mms.module.jiaGongSemi.dao.SemiOutDao;
import com.zhongwang.mms.module.jiaGongSemi.model.JSemi;
import com.zhongwang.mms.module.jiaGongSemi.model.JSemiDetail;
import com.zhongwang.mms.module.jiaGongSemi.model.JSemiInBillModel;
import com.zhongwang.mms.module.jiaGongSemi.model.JSemiInventory;
import com.zhongwang.mms.module.purchase.model.VWProject;
import com.zhongwang.mms.module.system.log.LogService;
import com.zhongwang.mms.util.BigDecimalUtils;
import com.zhongwang.mms.util.ShiroUtils;
import com.zhongwang.mms.util.StringUtils;
import lombok.extern.log4j.Log4j2;
import lombok.var;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * @ClassName： AllocationManageService
 * @Description： 库存查询业务逻辑层
 * @Author： China.zh
 * @Date： 2020/4/6 13:41
 * @Version： V1.0
 **/
@Log4j2
@Service
public class SemiOutService {


    @Autowired
    private LogService logService;
    @Value("${user.upload.path}")
    private String uploadPath;
    @Autowired
    private SemiOutDao semiOutDao;
    @Autowired
    private SemiInDao semiInDao;
    @Autowired
    private SemiInService semiInService;
    @Autowired
    private BoardService boardService;

    //查询库存列表
    public List<JSemiDetail> outOfFinishWar(JSemiInventory query) {

        return semiOutDao.findHInventoryByQuery(query);
    }
    @Transactional
    public JsonResult saveHInBillModel(JSemiInBillModel hInBillModel) {

        JsonResult jsonResult = new JsonResult();
        List<String> result = new ArrayList<>();
        PrintListModel printListModel = new PrintListModel();
        //验证数量是否可以出库
        String msg = "";  // 返回提示信息

        // 1 校验保存数据可用性、存在不满足条件数据 整单不允许保存
        msg = checkOutValidate(hInBillModel, msg);
        if (msg.length() > 0) {
            msg = msg + "<br>可用在库库存量不足，保存失败！";
            jsonResult.setMsg(msg);
            jsonResult.setType(JsonResult.ResultType.ERROR);
            jsonResult.setData("保存失败");
            return jsonResult;
        }
        //验证出库时间是否为空
        for (var i = 0; i < hInBillModel.getInsertData().size(); i++) {
            if(hInBillModel.getInsertData().get(i).getOdaStorageDate() == null){
                result.add("\n第" + (i + 1) + "行" + " 出库日期 为空！");
            }
            if(hInBillModel.getInsertData().get(i).getOdaAvaNum() <= 0){
                result.add("\n第" + (i + 1) + "行" + " 数量 必须大于0！");
            }
        }
        if (result.size() > 0) {
            result.add("\n单据保存失败，请先维护以上物料信息！");
            printListModel.setList(result);
            printListModel.setId(hInBillModel.getFormData().getOdrId());
            jsonResult.setData(printListModel);
            return jsonResult;
        }
        hInBillModel.getFormData().setOdrType(2);//1入库2出库
        hInBillModel.getFormData().setOdrStatus(0);//1调拨0其他

        //保存主单信息
        JSemi hOrderForm = saveOutHOrder(hInBillModel);

        JSemiDetail hOrderDetailModel = new JSemiDetail();
        //遍历表单内容
        for (var i = 0; i < hInBillModel.getInsertData().size(); i++) {

            //获取表单明细
            hOrderDetailModel = hInBillModel.getInsertData().get(i);
            //获取主单ID
            hOrderDetailModel.setOdrId(hInBillModel.getFormData().getOdrId());
            //物料分类
            hOrderDetailModel.setOdaMatType(2);//1是外购件、2是外协件、3是制作件
            //物料编码
            hOrderDetailModel.setOdaMatCode("1111111111");
            //红冲标识
            hOrderDetailModel.setOdaRedFlag(0);
            //保存表单明细
            semiInService.saveJSemiDetail(hOrderDetailModel);
            //保存库存信息
            saveOutHInventory(hOrderDetailModel);

        }
        result.add("单据保存成功！");
        logService.saveLog("【甲供件】毛坯件出库","出库单据编码：" +hOrderForm.getOdrCode());
        printListModel.setList(result);
        printListModel.setId(hInBillModel.getFormData().getOdrId());
        jsonResult.setData(printListModel);
        jsonResult.setType(JsonResult.ResultType.SUCCESS);
        return jsonResult;
    }
    /**
     * 出库保存库存信息
     * @param hOrderDetailModel
     * @return
     */
    public JSemiDetail saveOutHInventory(JSemiDetail hOrderDetailModel) {

        //封装库存信息
        HInventory hInventory = new HInventory();
        hInventory.setItyAvaNum(hOrderDetailModel.getOdaAvaNum());//出库数量
        hInventory.setItyId(hOrderDetailModel.getItyId());
        hInventory.setItyAvaWeight(hOrderDetailModel.getOdaWeight());
        semiOutDao.updateHInventoryById(hInventory);
        return hOrderDetailModel;
    }

    /**
     * 出库保存主单
     * @param hInBillModel
     * @return
     */
    public JSemi saveOutHOrder(JSemiInBillModel hInBillModel) {
        // 保存入库单主单信息
        JSemi hOrderForm = new JSemi();
        // 获取登入用户实体
        User user = ShiroUtils.getUser();

        hOrderForm = hInBillModel.getFormData();//总单信息
        hOrderForm.setOdrDate(new Date());//制单时间
        hOrderForm.setOdrCode(getOutOrderCode());//单据号
        hOrderForm.setOdrTakePerson(user.getName());//制单人
        hOrderForm.setOdrRedFlag(0); //红冲标识
        hOrderForm.setOdrItyFlag(1); //1蓝单2红单

        //保存主单信息
        semiInDao.insertSemi(hOrderForm);

        return hOrderForm;
    }
    //出库单号
    public String getOutOrderCode(){
        // 取得当日零时时间
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        Date date = calendar.getTime();
        // 查询当日是否有出库记录
        List<JSemi> hOrder = semiOutDao.findAllOutByDate(date);
        String orderCode; // 入库单编号生产规则：HRK200317001
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");

        if (hOrder.size() == 0) {
            orderCode = "HCK" + dateFormat.format(new Date()).substring(2,8) + "001";
        } else {
            orderCode = "HCK" + dateFormat.format(new Date()).substring(2,8) + String.format("%03d", Integer.parseInt(hOrder.get(0).getOdrCode().substring(10, 12)) + 1);
        }
        return orderCode;
    }
    /**
     * 校验出库单数据可用性
     *
     * @param hInBillModel
     * @return
     */
    public String checkOutValidate(JSemiInBillModel hInBillModel, String msg) {

        // 循环判断可用在库库存量是否充足（提示内容 可用在库库存量不足，保存失败！）
        JSemiInventory inventory;
        JSemiDetail orderDetailModel;
        List<JSemiDetail> orderDetailModelList = new ArrayList<>();

        for (int i = 0; i < hInBillModel.getInsertData().size(); i++) {
            if (hInBillModel.getInsertData().get(i).getItyId() == null) {
                continue;
            }

            // 同张单据多条数据相同时，需要将出库数量累加之后再进行库存是否充足校验
            boolean sameFlg = false;
            for (int j = 0; j < orderDetailModelList.size(); j++) {
                if (sameFlg) {
                    break;
                }
                Integer insertDetailId = hInBillModel.getInsertData().get(i).getItyId();
                Integer outDetailId = orderDetailModelList.get(j).getItyId();
                if (insertDetailId.intValue() == outDetailId.intValue()) {
                    orderDetailModelList.get(j).setOdaNum(BigDecimalUtils.add(orderDetailModelList.get(j).getOdaNum(), hInBillModel.getInsertData().get(i).getOdaAvaNum()));
                    sameFlg = true;
                }
            }
            if (!sameFlg) {
                orderDetailModel = new JSemiDetail();
                orderDetailModel.setItyId(hInBillModel.getInsertData().get(i).getItyId());
                orderDetailModel.setOdaNum(hInBillModel.getInsertData().get(i).getOdaAvaNum());
                orderDetailModelList.add(orderDetailModel);
            }
        }

        for (var i = 0; i < orderDetailModelList.size(); i++) {

            // 取得原料在库明细信息，与实际出库量进行比对，判断库存是否充足
            inventory = semiInDao.selectJSemiInventoryById(orderDetailModelList.get(i).getItyId());

            double a = inventory.getItyAvaNum();
            double c = orderDetailModelList.get(i).getOdaNum();
            if (a < c) {
                if(hInBillModel.getInsertData().get(i).getOdaMatType()!= null && hInBillModel.getInsertData().get(i).getOdaMatType() == 4){
                    msg = msg + "<br>" + hInBillModel.getInsertData().get(i).getOdaMatName() + " " + hInBillModel.getInsertData().get(i).getOdaTexture() + " " + hInBillModel.getInsertData().get(i).getOdaSpec()  ;
                }else {
                    msg = msg + "<br>" + hInBillModel.getInsertData().get(i).getOdaMatName();
                }
            }
        }
        return msg;
    }
    /**
     * 打印查询主单信息
     *
     * @param id
     * @return
     */
    public JsonResult selectHOrderById(Integer id) {

        JsonResult jsonResult = new JsonResult();
        JSemiDetail hOrder = semiOutDao.findAllById(id);
        jsonResult.setData(hOrder);
        return jsonResult;
    }
    /**
     * 根据主单ID查询子单信息
     *
     * @param id
     * @return
     */
    public JsonResult selectHOrderDetailByOdrId(Integer id) {

        JsonResult jsonResult = new JsonResult();
        List<JSemiDetail> hOrderDetailModels = semiOutDao.findAllByOdrId(id);
        jsonResult.setData(hOrderDetailModels);
        return jsonResult;
    }

}
